﻿

public class TreeNode {
    public int val;
    public TreeNode left;
    public TreeNode right;
    public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}

public class Solution {
    public TreeNode InvertTree(TreeNode root)
    {
        // 后序遍历，进行反转
        Stack<TreeNode> stack = new Stack<TreeNode>();
        if (root is not null) stack.Push(root);
        TreeNode node;
        while (stack.Count > 0)
        {
            node = stack.Peek();
            if (node is not null)
            {
                stack.Pop();
                stack.Push(node);
                stack.Push(null);
                if (node.right is not null) stack.Push(node.right);
                if (node.left is not null) stack.Push(node.left);
            }
            else
            {
                stack.Pop();
                node = stack.Pop();
                (node.left, node.right) = (node.right, node.left);
            }
        }
        return root;
    }

    public static void Main(string[] args)
    {
        int?[] root = [4, 2, 7, 1, 3, 6, 9];
        TreeNode rootNode = CreateBinaryTree(root);
        Solution solution = new Solution();
        rootNode = solution.InvertTree(rootNode);
        
        // 层次遍历并打印
        LayerTreePrint(rootNode);
    }

    private static void LayerTreePrint(TreeNode rootNode)
    {
        Queue<TreeNode> queue = new Queue<TreeNode>();
        if (rootNode is not null) queue.Enqueue(rootNode);
        int size;
        TreeNode node;
        while (queue.Count > 0)
        {
            size = queue.Count;
            for (int i = 0; i < size; i++)
            {
                node = queue.Dequeue();
                Console.Write($"{node.val} ");
                if (node.left is not null) queue.Enqueue(node.left);
                if (node.right is not null) queue.Enqueue(node.right);
            }
        }
    }

    private static TreeNode CreateBinaryTree(int?[] root)
    {
        if (root is null || root.Length == 0 || root[0] is null)
        {
            return null;
        }

        Queue<TreeNode> queue = new Queue<TreeNode>();
        TreeNode rootNode = new TreeNode(root[0].Value);
        queue.Enqueue(rootNode);
        int i = 1;
        TreeNode node;

        while (i < root.Length && queue.Count > 0)
        {
            node = queue.Dequeue();
            if (root[i] is not null)
            {
                node.left = new TreeNode(root[i].Value);
                queue.Enqueue(node.left);
            }

            i++;
            if (i >= root.Length) break;
            if (root[i] is not null)
            {
                node.right = new TreeNode(root[i].Value);
                queue.Enqueue(node.right);
            }

            i++;
        }

        return rootNode;
    }
}
